﻿using CarNetwork;
using System;

public class GameApplication
{
    private const string GameConfigPathFilename = "GameConfig.txt";

    private bool mShouldQuit;
    private GameSystemManager mGameSystemManager = new GameSystemManager();
    private GameCore mGameCore = new GameCore();

    public void Awake()
    {
        mGameSystemManager.Awake();
        mGameCore.Awake();
    }

    public void Start()
    {
        GameConfigManager.Instance.LoadConfigFile(GameConfigPathFilename);
        GameDocument.Instance.StartDocuments();

        StartNetwork();
        StartDatabase();

        mGameSystemManager.Start();
        mGameCore.Start();
    }

    public void Update()
    {
        mGameSystemManager.Update();
        mGameCore.Update();
    }

    public void Destroy()
    {
        GameNetwork.Instance.Stop();
        GameNetwork.Instance.Destroy();

        MySqlAccessor.Instance.Close();
        MySqlAccessor.Instance.Dispose();

        mGameSystemManager.Destroy();
        mGameCore.Destroy();
    }

    public bool ShouldQuit()
    {
        return mShouldQuit;
    }

    public void Quit()
    {
        mShouldQuit = true;
    }

    private void StartNetwork()
    {
        string tcpPortString = GameConfigManager.Instance.GetValue(GameConfigManager.TcpPort);
        int tcpPort = int.Parse(tcpPortString);

        string timeoutTimeString = GameConfigManager.Instance.GetValue(GameConfigManager.TimeoutTime);
        int timeoutTime = int.Parse(timeoutTimeString);
        GameNetwork.Instance.TimeoutTime = timeoutTime;
        GameNetwork.Instance.Awake();
        GameNetwork.Instance.Start(tcpPort);
    }

    private void StartDatabase()
    {
        string connectionString = GameConfigManager.Instance.GetValue(GameConfigManager.ConnectionString);
        MySqlAccessor.Instance.Start(connectionString);
    }
}
